﻿using System;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.Text;
using System.Web.UI.WebControls;
using Microsoft.SharePoint.Utilities;
using System.Threading;
using System.Web.UI;

namespace SPDatasheet.Layouts.SPDatasheet
{
    public partial class Datasheet : LayoutsPageBase
    {
        protected void Page_Load(object sender, EventArgs e)
        {
        }

        protected void setPageTitle(string title)
        {
            // Set Page Title
            ContentPlaceHolder contentPlaceHolder = (ContentPlaceHolder)Page.Master.FindControl("PlaceHolderPageTitleInTitleArea");
            contentPlaceHolder.Controls.Clear();
            LiteralControl literalControl = new LiteralControl();
            literalControl.Text = title;
            contentPlaceHolder.Controls.Add(literalControl);
        }

        protected override void CreateChildControls()
        {
            try
            {
                base.CreateChildControls();
                if (Request["RootFolder"] == null) throw new Exception("The RootFolder Query String is missing.");
                if (Request["View"] == null) throw new Exception("The View Query String is missing.");                

                SPList list = SPContext.Current.Web.GetList(Request["RootFolder"]);
                SPView view = list.Views[Guid.Parse(Request["View"])];
                SPFolder rootFolder = Web.GetFolder(Request["RootFolder"]);
                SPQuery query = new SPQuery {ViewXml = view.SchemaXml, Folder = rootFolder};
                SPListItemCollection items = list.GetItems(query);

                setPageTitle(list.Title);

                StringBuilder htmlObject = new StringBuilder();
                htmlObject.Append("<object id=\"STSListControlWPQ2\" name=\"STSListControlWPQ2\" classid=\"CLSID:65BCBEE4-7728-41a0-97BE-14E1CAE36AAE\" class=\"ms-dlgDisable\" width=\"99%\" tabIndex=\"1\">\r\n");
                htmlObject.AppendFormat("<param name=\"ListName\" value=\"{0}\">\r\n", list.ID);
                htmlObject.AppendFormat("<param name=\"ViewGuid\" value=\"{0}\">\r\n,", view.ID);
                htmlObject.AppendFormat("<param name=\"RootFolder\" value=\"{0}\">\r\n", rootFolder.ServerRelativeUrl);
                htmlObject.AppendFormat("<param name=\"ListWeb\" value=\"{0}/_vti_bin\">\r\n", SPContext.Current.Web.Url);
                htmlObject.AppendFormat("<param name=\"ListData\" value=\"{0}\">\r\n", SPEncode.HtmlEncode(items.Xml));
                htmlObject.AppendFormat("<param name=\"ViewSchema\" value=\"{0}\">\r\n", SPEncode.HtmlEncode(view.SchemaXml));
                htmlObject.AppendFormat("<param name=\"ListSchema\" value=\"{0}\">\r\n", SPEncode.HtmlEncode(list.SchemaXml));
                htmlObject.Append("<param name=\"ControlName\" value=\"STSListControlWPQ2\">\r\n\r\n");
                htmlObject.AppendFormat("<p class=\"ms-descriptiontext\">The Datasheet view of this list cannot be displayed. This could be due to a number of reasons, such as not having Microsoft Office installed or using a browser which doesnt support ActiveX (Chrome, Firefox or Safari).<a href=\"{0}\" target=_self>Open the list in Standard view</a></p>", rootFolder.ServerRelativeUrl);
                htmlObject.Append("</object>");
                
                Literal literal = new Literal();
                literal.Text = string.Format("<script>RenderActiveX(\"{0}\");</script>", SPEncode.ScriptEncode(htmlObject.ToString()));
                PlaceHolderSPDatasheet.Controls.Add(literal);
            }
            catch (ThreadAbortException) { /* Thrown when redirected */}
            catch (Exception ex)
            {
                SPUtility.TransferToErrorPage(ex.Message);
            }
        }
    }
}
